// http://www.axios-js.com/docs/#axios-create-config
import axios from "axios";
import {notification} from "antd";
const config = require('./config');

export const axiosInstance = axios.create({
  timeout: 2000,
  baseURL: `${config.mock.local.target}`,
  headers: {"X-Requested-With": "XMLHttpRequest"}
});

// http request 拦截器
axios.interceptors.request.use(
  req => {
    Object.assign(req.headers.common, {
      // ...
    });
    return req;
  },
  error => Promise.reject(error)
);

axiosInstance.interceptors.response.use(
  res => {
    // console.log('axiosInstance', res);
    if (res.status !== 200) {
      notification.error({
        message: `${res.data.title} 请求失败`
      });
      return Promise.reject(res);
    } else if (!res.data.success) {
      notification.error({
        message: `${res.data.title} 错误：${res.data.msg}`
      });
      return Promise.reject(res);
    }
    return res;
  },
  error => {
    if (error.response.status > 400) {
      notification.error({
        message: `错误状态码：${error.response.status}`
      });
    }
    return Promise.reject(error);
  }
);

export default function(config) {
  if (config.title) {
    if (!config.transformResponse) {
      config.transformResponse = [];
    }
    Array.isArray(config.transformResponse) &&
      config.transformResponse.push(data => ({
        ...JSON.parse(data),
        title: config.title
      }));
  }

  return axiosInstance(config).catch(function(res) {
    return res;
  });
}
